import {
  getPlantCapacityBaseByPage,
  addPlantCapacityBase,
  updatePlantCapacityBase,
  delPlantCapacityBase,
  exportPlantCapacityBase,
  getAllFactory,
  getAllProcess,
  judgePlantCapacityBaseByProcessCode,
} from '@/services/baseData/plantCapacityBase';
import {
  getPlantCapacityCalendarByPage,
  addPlantCapacityCalendar,
  updatePlantCapacityCalendar,
  delPlantCapacityCalendar,
  exportPlantCapacityCalendar,
  getAllPlantCapacityCalendar,
  getPlantCapacityBase,
} from '@/services/product/plantCapacityCalendar';
import { PlusOutlined, AreaChartOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Select,
  InputNumber,
  Tabs,
  Row,
  Col,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { Fragment, useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { tabType } from '../product/components/interfaceProduct';
import { DualAxes } from '@ant-design/charts';
import dayjs from '@/components/dayjs';
import '../product/product.module.less';
import { Ellipsis } from '@/components/Ellipsis';
import WrokingHoursOverView from '../product/wrokingHoursOverView';
import moment from 'moment';
import PlantCapacityBaseStatisticsTable from '../product/plantCapacityBaseStatisticsTable';
const PlantCapacityBase: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const actionRef_2 = useRef<ActionType>();
  const actionRef_3 = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [optionsProcess, setoptionsProcess] = useState([]); //工序下拉框用到
  const [nameforsearch, setnameforsearch] = useState([]); //工序下拉框用到
  const [codeforsearch, setcodeforsearch] = useState([]); //工序下拉框用到
  const [proname, setproname] = useState();
  const [procode, setprocode] = useState();
  const [optionsfactory, setoptionsfactory] = useState([]); //下拉框用到

  const [confirmLoading2, setConfirmLoading2] = useState(false); //统计图的disable
  const [modalVisit2, setModalVisit2] = useState(false); // 产能负荷图

  const [uvData, setuvData] = useState([]);
  const [transformData, settransformData] = useState([]);

  const [form] = Form.useForm();
  const ref = useRef(null);
  const dateFormat = 'YYYY-MM-DD';

  const initialForm = {
    date: '10',
    process: 'all',
  };

  // 产能基础数据
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 60,
    },
    {
      title: '工序名称',
      dataIndex: 'processName',
      valueType: 'select',
      request: async () => {
        const getprocesslist = await getAllProcess(null);
        const processname: { label: any; value: any }[] = [];
        getprocesslist.data.map((item: any, index: any) => {
          processname.push({ label: item.processName, value: item.processName });
        });
        return processname;
      },

      align: 'center',
      sorter: true,
      width: 140,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',
      valueType: 'select',
      request: async () => {
        const getprocesslist = await getAllProcess(null);
        // 获取工序编号
        const processcode: any[] = [];
        getprocesslist.data.map((item: any, index: any) => {
          processcode.push({ label: item.processCode, value: item.processCode });
        });
        return processcode;
      },

      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '人数',
      dataIndex: 'workerQty',
      align: 'center',
      sorter: true,
      search: false,
      width: 80,
    },
    {
      title: '每天正常工作时长(h)',
      dataIndex: 'normalTime',
      align: 'center',
      sorter: true,
      search: false,
      width: 140,
      render: (text, record, _, action) => {
        return <div>{record.normalTime.toFixed(2)}</div>;
      },
    },
    {
      title: '每天班次数(次)',
      dataIndex: 'shiftQty',
      align: 'center',
      sorter: true,
      search: false,
      width: 100,
    },
    {
      title: '工作效率(%)',
      dataIndex: 'efficiency',
      align: 'center',
      sorter: true,
      search: false,
      render: (text, record, _, action) => {
        return <div>{record.efficiency.toFixed(2)}</div>;
      },
      width: 100,
    },
    {
      title: '正常产能(h)',
      dataIndex: 'normalCapacity',
      align: 'center',
      sorter: true,
      search: false,
      width: 100,
      render: (text, record, _, action) => {
        return <div>{record.normalCapacity.toFixed(2)}</div>;
      },
    },
    {
      title: '加班时长(h)',
      dataIndex: 'overTime',
      align: 'center',
      sorter: true,
      search: false,
      width: 100,
      render: (text, record, _, action) => {
        return <div>{record.overTime.toFixed(2)}</div>;
      },
    },
    {
      title: '加班产能(h)',
      dataIndex: 'overtimeCapacity',
      align: 'center',
      sorter: true,
      search: false,
      width: 100,
      render: (text, record, _, action) => {
        return <div>{record.overtimeCapacity.toFixed(2)}</div>;
      },
    },
    {
      title: '总产能(h)',
      dataIndex: 'totalCapacity',
      align: 'center',
      sorter: true,
      search: false,
      width: 100,
      render: (text, record, _, action) => {
        return <div>{record.totalCapacity.toFixed(2)}</div>;
      },
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      width: 100,
      render: (text, record, _, action) => {
        return dayjs(record.createTime).format(dateFormat);
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              efficiency: record.efficiency,
              normalTime: record.normalTime,
              overTime: record.overTime,
              processCode: record.processCode,
              processName: record.processName,
              shiftQty: record.shiftQty,
              workerQty: record.workerQty,
              normalCapacity: record.normalCapacity,
              overtimeCapacity: record.overtimeCapacity,
              totalCapacity: record.totalCapacity,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delPlantCapacityBase({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  // 实际产能数据
  const actualColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      width: 110,

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      width: 100,

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '批次编号',
      dataIndex: 'batchPlanCode',
      width: 200,

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '工序名称',
      dataIndex: 'processName',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getprocesslist = await getAllProcess(null);
        const processname: { label: any; value: any }[] = [];
        getprocesslist.data.map((item: any, index: any) => {
          processname.push({ label: item.processName, value: item.processName });
        });
        return processname;
      },
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',

      align: 'center',
      sorter: true,
      valueType: 'select',
      request: async () => {
        const getprocesslist = await getAllProcess(null);
        // 获取工序编号
        const processcode: any[] = [];
        getprocesslist.data.map((item: any, index: any) => {
          processcode.push({ label: item.processCode, value: item.processCode });
        });
        return processcode;
      },
    },
    {
      title: '计划工时(h)',
      dataIndex: 'workHour',

      align: 'center',
      sorter: true,
      valueType: 'digit',
      search: false,
    },
    {
      title: '实际工时(h)',
      dataIndex: 'realWorkHour',

      align: 'center',
      sorter: true,
      valueType: 'digit',
      search: false,
    },
    {
      title: '日期',
      dataIndex: 'date',

      valueType: 'date',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '日期',
      dataIndex: 'date',
      hideInTable: true,
      valueType: 'dateRange',
    },
    {
      title: '加工顺序编号',
      dataIndex: 'processSequence',

      align: 'center',
      sorter: true,
      valueType: 'digit',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      render: (text, record, _, action) => {
        return dayjs(record.createTime).format(dateFormat);
      },
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',
    },
  ];
  const hourColumns: ProColumns[] = [];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.processCode = procode;
          res.processName = proname;
          res.overTime = parseFloat(res.overTime).toFixed(2);
          res.efficiency = parseFloat(res.efficiency).toFixed(2);
          res.normalTime = parseFloat(res.normalTime).toFixed(2);
          console.log(res);
          const judge = await judgePlantCapacityBaseByProcessCode(res.processCode);
          console.log(judge);
          if (judge.data == null) {
            const result = await addPlantCapacityBase(res);
            if (result != null) {
              message.success('添加成功');
              setConfirmLoading(false);
              setModalVisit(false);
              actionRef.current!.reload();
            }
          } else {
            message.warning('该工序已存在产能');
            setConfirmLoading(false);
            // setModalVisit(false);
            // actionRef.current!.reload();
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.overTime = parseFloat(res.overTime).toFixed(2);
          res.efficiency = parseFloat(res.efficiency).toFixed(2);
          res.normalTime = parseFloat(res.normalTime).toFixed(2);
          const result = await updatePlantCapacityBase(res);
          if (result != null) {
            message.success('修改成功');
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current!.reload();
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  //获取工序
  const getprocess = async () => {
    const getprocesslist = await getAllProcess(null);
    const processOptionContract = [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.processCode, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
    // 获取工序名称
    const processname: { label: any; value: any }[] = [];
    getprocesslist.data.map((item: any, index: any) => {
      processname.push({ label: item.processName, value: item.processName });
    });
    setnameforsearch(processname);
    // 获取工序编号
    const processcode = [];
    getprocesslist.data.map((item: any, index: any) => {
      processcode.push({ label: item.processCode, value: item.processCode });
    });
    setcodeforsearch(processcode);
  };

  //保存下拉框的工序名称和编号
  const changeprocess = async (value: { value: string; label: React.ReactNode }) => {
    setproname(value.label);
    setprocode(value.value);
  };

  const get_select = async () => {
    // 获取工序（下拉框）tab3
    const getprocesslist = await getAllProcess(null);
    const processOptionContract = [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.id, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
  };

  const dealwith_data = async () => {
    // 初始化柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: '',
      range: 10,
    };
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, 实际产能: item.capacityLoad });
    });
    setuvData(thedata);
    // 初始化横线数据
    const basicsdata = await getPlantCapacityBase({ processId: null });
    const thedata_basic = [];
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.normalCapacity,
        name: '正常产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.overtimeCapacity,
        name: '加班产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({ time: item.date, count: basicsdata.data.totalCapacity, name: '总产能' });
    });
    settransformData(thedata_basic);
  };

  const handleSubmit_data = async () => {
    const res = form.getFieldsValue();
    // 更新柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: res.process == 'all' ? 'null' : res.process,
      range: res.date == undefined ? 10 : res.date,
    };
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, 实际产能: item.capacityLoad });
    });
    setuvData(thedata);
    // 更新横线数据
    const basicsdata = await getPlantCapacityBase({
      processId: res.process == 'all' ? 'null' : res.process,
    });
    const thedata_basic = [];
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.normalCapacity,
        name: '正常产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.overtimeCapacity,
        name: '加班产能',
      });
    });
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({ time: item.date, count: basicsdata.data.totalCapacity, name: '总产能' });
    });
    settransformData(thedata_basic);
  };

  const config = {
    data: [uvData, transformData],
    xField: 'time',
    yField: ['实际产能', 'count'],
    geometryOptions: [
      {
        geometry: 'column',
        columnWidthRatio: 0.4,
      },
      {
        geometry: 'line',
        seriesField: 'name',
      },
    ],
  };

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '基础产能',
      content: (
        <div>
          <ProTable
            headerTitle="产能基础数据管理"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              labelWidth: 100,
              defaultCollapsed: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle('新建');
                  form.resetFields();
                  setModalVisit(true);
                }}
                type="primary"
              >
                新建
              </Button>,
              // <Button
              //   key="button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     const filters = filterTranNew(ref.current.getFieldsValue());
              //     exportPlantCapacityBase({
              //       current: 1,
              //       pageSize: 5000,
              //       filters: filters,
              //     }).then((res) => {
              //       const aLink = document.createElement('a');
              //       document.body.appendChild(aLink);
              //       aLink.style.display = 'none';
              //       aLink.href = window.URL.createObjectURL(res);
              //       aLink.setAttribute('download', `PlantCapacityBase.xlsx`);
              //       aLink.click();
              //       document.body.removeChild(aLink);
              //     });
              //   }}
              //   type="primary"
              // >
              //   导出
              // </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              getprocess();
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const result = await getPlantCapacityBaseByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 2000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '实际产能',
      content: (
        <div>
          <ProTable
            headerTitle="实际产能管理"
            actionRef={actionRef_2} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              labelWidth: 100,
              defaultCollapsed: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                type="primary"
                onClick={() => {
                  setModalVisit2(true)
                }}
              >
                产能负荷图
              </Button>
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const result = await getPlantCapacityCalendarByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              get_select();
              dealwith_data();
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={actualColumns}
            scroll={{ x: 1600, y: 350 }}
            rowSelection={{}}
          />
          <Modal
            title="产能负荷图"
            width={1200}
            open={modalVisit2}
            onCancel={() => {
              setModalVisit2(false);
            }}
            destroyOnClose
            footer={null}
          >
            <PlantCapacityBaseStatisticsTable />
          </Modal>
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '工时统计',
      content: <WrokingHoursOverView></WrokingHoursOverView>,
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        type="card"
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        width={600}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '160px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item name="id" label="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="工序名称"
            name="processName"
            rules={[{ required: true, message: '请选择工序!' }]}
          >
            <Select
              placeholder="请选择工序"
              onChange={changeprocess}
              options={optionsProcess}
              disabled={createOrUpdate}
              labelInValue
            />
          </Form.Item>
          <Form.Item
            name="processCode"
            label="工序编号"
            // rules={[{ required: true, message: '请输入工序编号!' }]}
            hidden={!createOrUpdate}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            name="workerQty"
            label="人数"
            rules={[{ required: true, message: '请输入人数!' }]}
          >
            <InputNumber addonAfter="人" min={0} max={99999} precision={0} style={{ width: 390 }} />
          </Form.Item>
          <Form.Item
            name="normalTime"
            label="每天正常工作时长(h)"
            rules={[{ required: true, message: '请输入每天正常工作时长!' }]}
          >
            <InputNumber
              style={{ width: 390 }}
              min={0}
              max={24}
              addonAfter="h"
              step="0.01"
              // defaultValue="1"
              // min="0"
              // max="100"
              // step="0.00000000000001"
              // onChange={onChange}
              stringMode
            />
          </Form.Item>
          <Form.Item
            name="shiftQty"
            label="每天班次数"
            rules={[{ required: true, message: '请输入每天班次数!' }]}
          >
            <InputNumber addonAfter="次" min={0} max={99999} precision={0} style={{ width: 390 }} />
          </Form.Item>
          <Form.Item
            name="efficiency"
            label="工作效率"
            rules={[{ required: true, message: '请输入工作效率!' }]}
          >
            <InputNumber
              style={{ width: 390 }}
              min={0}
              max={100}
              step="0.01"
              addonAfter="%"
              // step="0.00000000000001"
              // onChange={onChange}
              stringMode
            />
          </Form.Item>
          <Form.Item
            name="overTime"
            label="加班时长"
            rules={[{ required: true, message: '请输入加班时长!' }]}
          >
            <InputNumber
              min={0}
              max={24}
              style={{ width: 390 }}
              addonAfter="h"
              step="0.01"
              // defaultValue="1"
              // min="0"
              // max="100"
              // step="0.00000000000001"
              // onChange={onChange}
              stringMode
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default PlantCapacityBase;
